//
//  XPEmojiDisplayCell.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/20.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit


let XPEmojiDisplayCellNotificationName = "XPEmojiDisplayCellNotificationName"
class XPEmojiDisplayCell: UICollectionViewCell {
    
    let displayLabel: UILabel = UILabel(color: UIColor.whiteColor(), fontSize: 30)
    
    lazy var emojiButtons: [XPKeyboardButton] = [XPKeyboardButton]()
    
//    var indexPath: NSIndexPath? {
//        didSet {
//            displayLabel.text = "当前是第\(indexPath!.section)第\(indexPath!.item)行"
//            displayLabel.textColor = UIColor.whiteColor()
//        }
//    }
    
    var emoticons: [XPEmoticon]? {
        didSet {
            guard let emt = emoticons else { return }
            
            for button in emojiButtons {
                button.hidden = true
            }
            
            for (i, value) in emt.enumerate() {
                let button = emojiButtons[i]
                button.emoticon = value
                button.hidden = false
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor.whiteColor()
        addChildButton()
        contentView.addSubview(displayLabel)
        
//        displayLabel.snp_makeConstraints { (make) -> Void in
//            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
//        }
    }
    
    private func addChildButton() {
        for _ in 0..<20 {
            let button = XPKeyboardButton()
            button.addTarget(self, action: #selector(XPEmojiDisplayCell.keyboardClicked(_:)), forControlEvents: .TouchUpInside)
            button.titleLabel?.font = UIFont.systemFontOfSize(32)
            contentView.addSubview(button)
            emojiButtons.append(button)
        }
    }
    
    @objc private func keyboardClicked(button: XPKeyboardButton) {
        NSNotificationCenter.defaultCenter().postNotificationName(XPEmojiDisplayCellNotificationName, object: button.emoticon)
    }
    
    /// 设置每个按钮frame
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let buttonWidth = width / 7
        let buttonHeight = height / 3
        for (i, button) in emojiButtons.enumerate() {
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            let columns = i % 7
            let rows = i / 7
        
            button.x = CGFloat(columns) * buttonWidth
            button.y = CGFloat(rows) * buttonHeight
        }
    }
}
